<template>
  <div>
    <el-card class="box-card">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="username" placeholder="用户名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search">查询</el-button>
          <el-button>清空</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="addUser">添加</el-button>
      <el-button type="danger">批量删除</el-button>
      <el-table :data="tableData" border style="width: 100%" class="User-table">
        <el-table-column type="selection" width="60" />
        <el-table-column type="index" label="序号" width="180" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="nickName" label="用户昵称" />
        <el-table-column prop="roleName" label="角色列表" width="180" />
        <el-table-column prop="gmtCreate" label="创建时间" width="180" />
        <el-table-column prop="gmtModified" label="更新时间" width="180" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              :icon="UserFilled"
              type="info"
              style="color: #ffffff"
              @click="Distribute(row)"
            ></el-button>
            <el-button type="success" :icon="Check"></el-button>
            <el-button type="danger" :icon="Delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:currentPage="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :small="true"
        layout=" prev, pager, next, jumper,  ->, sizes, total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 对话框来做  需要表单收集的 弹窗   开始-->
    <el-dialog v-model="UserVisible" title="添加用户" width="30%">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="checkPass">
          <el-input v-model="ruleForm.nickName" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="ruleForm.password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 对话框来做  需要表单收集的 弹窗   结束-->

    <!-- 分配权限  开始 -->
    <el-dialog v-model="DistributeVisible" title="设置角色" width="30%">
      <el-form label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="assignRoleFormData.username" :disabled="true" />
        </el-form-item>
      </el-form>
      <el-form-item label="角色列表">
        <el-checkbox
          v-model="assignRoleFormData.checkAll"
          @change="handleCheckAllChange"
          :indeterminate="assignRoleFormData.isIndeterminate"
          >全选
        </el-checkbox>
        <el-checkbox-group
          v-model="assignRoleFormData.roleId"
          @change="handleCheckedChange"
        >
          <el-checkbox
            v-for="role in assignRoleFormData.allRolesList"
            :key="role.id"
            :label="role.id"
          >
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="setUpRole">保存</el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>
    </el-dialog>
    <!-- 分配权限  结束 -->
  </div>
</template>

<script lang="ts">
export default {
  name: "XUser",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { Search, UserFilled, Check, Delete } from "@element-plus/icons-vue";
import {
  getUserManageListApi,
  saveUserApi,
  getUserRoleListApi,
  assignUserRoleApi,
} from "@/Api/acl/user";
import type { UserItems, UserItem, RoleList } from "@/Api/acl/model/userModel";
//   element-plus  element 类型引入需要在js代码上面  引入  不然会报错
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";

// 这是选择第几页 获取第几页的数据
const currentPage = ref(1);
// 这是分页器一页显示多少条数据
const pageSize = ref(5);
// 这是分页器的总数的定义
const total = ref(0);
// 双向数据绑定获取查询的input框的 v-model 的值
const username = ref("");
// table 表达定义的数组
const tableData = ref<UserItems>([]);

// 定义对话框 的是否显示  默认不显示是false
const UserVisible = ref(false);

/****************** 添加用户按钮 功能对话框  和 对话框中的form 表单的代码 开始 *******************/
// 声明收集form表单的对象

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  username: "",
  nickName: "",
  password: "",
});
const rules = reactive<FormRules>({
  username: [{ required: true, message: "用户名必须输入", trigger: "blur" }],
  password: [{ required: true, message: "密码必须输入", trigger: "blur" }],
});

// submitForm 保存  表单校验过  发送请求
const submitForm = async () => {
  // 调用这个函数  表单严重会返回一个成功的promise  就会继续执行下面代码 否则代码停止执行
  await ruleFormRef.value?.validate();
  await saveUserApi(ruleForm);
  UserVisible.value = false;
  getUserList();
  ElMessage.success("添加用户成功");
};
// resetForm 取消 关闭 取消添加  关闭对话框
const resetForm = () => {
  UserVisible.value = false;
};

const addUser = () => {
  //  显示对象框
  UserVisible.value = true;
  // 添加功能一上来清空input上的v-model的值
  ruleForm.username = "";
  ruleForm.nickName = "";
  ruleForm.password = "";
};

/****************** 添加用户按钮 功能对话框  和 对话框中的form 表单的代码 结束 *******************/

// 封装请求User分页列表的 axios 请求
const getUserList = async () => {
  const res = await getUserManageListApi(
    currentPage.value,
    pageSize.value,
    username.value
  );
  total.value = res.total;
  tableData.value = res.items;
};

// 挂载的时候  发送分页数据请求
onMounted(() => {
  getUserList();
});

// 这是每页条数发生改变的时候触发的回调函数  更新每页条数 重新发送请求
const handleSizeChange = () => {
  getUserList();
};
// 这是哪一页发生改变的时候触发的回调函数  更新每页条数 重新发送请求
const handleCurrentChange = () => {
  getUserList();
};

/******************  分配页面 开始  ****************** */
// 分配权限的 对话框的显示与隐藏
const DistributeVisible = ref(false);
const assignRoleFormRef = ref<FormInstance>();

interface AssignRoleFormData {
  username: string;
  userId: string;
  roleId: string[];
  checkAll: boolean;
  isIndeterminate: boolean;
  allRolesList: RoleList;
}

const assignRoleFormData = reactive<AssignRoleFormData>({
  username: "",
  userId: "",
  roleId: [],
  checkAll: false, // 全选
  isIndeterminate: false, // 是否半选
  // assignRoles: [],
  allRolesList: [],
});

// 全选按钮的判断和操作
const handleCheckAllChange = (val: boolean | string | number) => {
  if (val) {
    assignRoleFormData.roleId = assignRoleFormData.allRolesList.map(
      (item) => item.id + ""
    );
  } else {
    assignRoleFormData.roleId = [];
  }
};

// 单选触发的回调   判断是否半选 全选 不选
const handleCheckedChange = () => {
  // console.log(2);
  assignRoleFormData.isIndeterminate =
    !!assignRoleFormData.roleId.length &&
    assignRoleFormData.roleId.length !== assignRoleFormData.allRolesList.length;
  assignRoleFormData.checkAll =
    assignRoleFormData.roleId.length === assignRoleFormData.allRolesList.length;
};

const Distribute = async (row: UserItem) => {
  const res = await getUserRoleListApi(row.id);
  assignRoleFormData.allRolesList = res.allRolesList;
  DistributeVisible.value = true;
  assignRoleFormData.username = row.username;
  assignRoleFormData.roleId = [];
};

// 设置角色保存 按钮的回调函数
const setUpRole = async () => {
  await assignRoleFormRef.value?.validate();
  await assignUserRoleApi(assignRoleFormData.userId, assignRoleFormData.roleId);
  ElMessage.success("修改角色设置");
  DistributeVisible.value = false;
};

/******************  分配页面 结束  ****************** */
</script>

<style scoped>
.User-table {
  margin: 20px 0;
}
</style>
